<?php
/**
 * Copyright (c) [2019] [吴跃忠]
 * [selibra] is licensed under the Mulan PSL v1.
 * You can use this software according to the terms and conditions of the Mulan PSL v1.
 * You may obtain a copy of Mulan PSL v1 at:
 * http://license.coscl.org.cn/MulanPSL
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
 * PURPOSE.
 * See the Mulan PSL v1 for more details.
 */

namespace Zooclient;

use Selibra\Config\Config;
use Selibra\Tools\Console;
use Swoole\ConnectionPool;
use Swoole\Coroutine;

class Connection
{
    protected static ConnectionPool $pool;

    protected static array $zookeeperCoroutine = [];

    protected static array $zookeeper = [];

    public static function getConnection(): \Zookeeper
    {
        if (!isset(self::$zookeeper[getmypid()])) {
            self::$zookeeper[getmypid()] = new \Zookeeper();
            self::connect();
        } else {
            // 判断连接状态
            if (self::$zookeeper[getmypid()]->getState() == false) {
                self::connect();
            }
        }
        return self::$zookeeper[getmypid()];
    }


    public static function getPool(): ConnectionPool
    {
        if (!isset(self::$pool)) {
            self::$pool = new ConnectionPool(function () {
                $zookeeper = new \Zookeeper();
                $zookeeper->connect(Config::get('zooclient.host'));
                return $zookeeper;
            }, Config::get('zooclient.pool_size'));
        }
        return self::$pool;
    }


    /**
     * 连接
     */
    public static function connect()
    {
        self::$zookeeper[getmypid()]->connect(Config::get('zooclient.host'));
    }

}
